# -*- coding: utf-8 -*-
'''
@Time    : 18-9-5 下午8:23
@Author  : qinpengzhi
@File    : logger.py
@Software: PyCharm
@Contact : qinpzhi@163.com
'''
import tensorflow as tf
import os
import logging


class DebugLogger():
    def __init__(self, log_file):
        logging.basicConfig(level=logging.DEBUG, \
                            format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', \
                            datefmt='%a, %d %b %Y %H:%M:%S', \
                            filename=log_file, \
                            filemode='w')
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
        console.setFormatter(formatter)
        logging.getLogger('').addHandler(console)

    def log_error(self, error_info):
        logging.error(error_info)


class TfLogger():
    def __init__(self, sess, config):
        self.sess = sess
        self.config = config
        self.summary_placeholders = {}
        self.summary_ops = {}
        self.train_summary_writer = tf.summary.FileWriter(os.path.join(self.config.summary_dir, "train"),
                                                          self.sess.graph)
        self.test_summary_writer = tf.summary.FileWriter(os.path.join(self.config.summary_dir, "test"))

    # it can summarize scalers and images.
    def summarize(self, step, summerizer="train", scope="", summaries_dict=None):
        """
        :param step: the step of the summary
        :param summerizer: use the train summary writer or the test one
        :param scope: variable scope
        :param summaries_dict: the dict of the summaries values (tag,value)
        :return:
        """
        summary_writer = self.train_summary_writer if summerizer == "train" else self.test_summary_writer
        with tf.variable_scope(scope):

            if summaries_dict is not None:
                summary_list = []
                for tag, value in summaries_dict.items():
                    if tag not in self.summary_ops:
                        self.summary_placeholders[tag] = tf.placeholder('float32', value.shape, name=tag)
                        if len(value.shape) <= 1:
                            self.summary_ops[tag] = tf.summary.scalar(tag, self.summary_placeholders[tag])
                        else:
                            self.summary_ops[tag] = tf.summary.image(tag, self.summary_placeholders[tag])

                    summary_list.append(self.sess.run(self.summary_ops[tag], {self.summary_placeholders[tag]: value}))

                for summary in summary_list:
                    summary_writer.add_summary(summary, step)
                summary_writer.flush()
